package com.sgcc.pda.ssal.mqtt.proxy.client;


import com.sgcc.pda.baselibrary.utils.LogUtil;
import com.sgcc.pda.ssal.mqtt.proxy.server.MqttProxyServer;

import java.util.Arrays;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by cj on 2020/1/10.
 * 收到paho前置返回时，通过前面的解码，这里拿到真正的paho需要要的mqtt消息
 * 通过代理server的channel写回去。
 */
public class MqttClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private static final String TAG = "mqtt";


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
//        LogUtil.e(TAG, "msg from mqttBroker: " + msg.readableBytes());
//        for (int i = 0; i < 4; i++) {
//            short b = msg.readUnsignedByte();
//            Log.e(TAG, "channelRead0:    "+b );
//        }
        byte[] bytes = new byte[msg.readableBytes()];
        msg.getBytes(0, bytes);
        LogUtil.e(TAG, "channelRead0: " + Arrays.toString(bytes));
        LogUtil.e(TAG, "代理客户端解码收到broker消息：" + msg.readableBytes() + "  " + Thread.currentThread().getName());
        ReferenceCountUtil.retain(msg);
        MqttProxyServer.sendMessage(msg);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        LogUtil.e(TAG, "exceptionCaught: " + cause.getMessage());
    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);

    }

}
